<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="在前面两节我们已经完成springboot操作mysql数据库，但是在实际业务场景中，数据量迅速增长，一个库一个表已经满足不了我们的需求的时候，我们就会考虑分库分表的操作，那么接下来我们就去学习一下，在springboot中如何实现多数据源，动态数据源切换，读写分离等操作。">
<meta name="keywords" content="SpringBoot,DynamicDataSource,DataSource">
<meta property="og:type" content="article">
<meta property="og:title" content="【SpringBoot2.0系列06】SpringBoot之多数据源动态切换数据源">
<meta property="og:url" content="http://www.yukonga.cn/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/index.html">
<meta property="og:site_name" content="yukong&#39;s blog">
<meta property="og:description" content="在前面两节我们已经完成springboot操作mysql数据库，但是在实际业务场景中，数据量迅速增长，一个库一个表已经满足不了我们的需求的时候，我们就会考虑分库分表的操作，那么接下来我们就去学习一下，在springboot中如何实现多数据源，动态数据源切换，读写分离等操作。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061637.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061626.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061705.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061715.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061727.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061734.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061823.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061834.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061845.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061853.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-061902.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-055539.jpg">
<meta property="og:updated_time" content="2019-05-07T06:19:11.069Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【SpringBoot2.0系列06】SpringBoot之多数据源动态切换数据源">
<meta name="twitter:description" content="在前面两节我们已经完成springboot操作mysql数据库，但是在实际业务场景中，数据量迅速增长，一个库一个表已经满足不了我们的需求的时候，我们就会考虑分库分表的操作，那么接下来我们就去学习一下，在springboot中如何实现多数据源，动态数据源切换，读写分离等操作。">
<meta name="twitter:image" content="http://cdn.yukonga.cn/2019-05-07-061637.jpg">



  <link rel="alternate" href="/atom.xml" title="yukong's blog" type="application/atom+xml">




  <link rel="canonical" href="http://www.yukonga.cn/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【SpringBoot2.0系列06】SpringBoot之多数据源动态切换数据源 | yukong's blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?45b7a3cfe46b3fa2c5d46f59f590664e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yukong's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">learning program</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.yukonga.cn/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yukong">
      <meta itemprop="description" content="你若对得起时间，时间便对得起你">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yukong's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【SpringBoot2.0系列06】SpringBoot之多数据源动态切换数据源

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-08-19 13:59:55" itemprop="dateCreated datePublished" datetime="2018-08-19T13:59:55+08:00">2018-08-19</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-05-07 14:19:11" itemprop="dateModified" datetime="2019-05-07T14:19:11+08:00">2019-05-07</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/SpringBoot/" itemprop="url" rel="index"><span itemprop="name">SpringBoot</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/" class="leancloud_visitors" data-flag-title="【SpringBoot2.0系列06】SpringBoot之多数据源动态切换数据源">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在前面两节我们已经完成springboot操作mysql数据库，但是在实际业务场景中，数据量迅速增长，一个库一个表已经满足不了我们的需求的时候，我们就会考虑分库分表的操作，那么接下来我们就去学习一下，在springboot中如何实现多数据源，动态数据源切换，读写分离等操作。</p>
<a id="more"></a>
<h1 id="实现"><a class="markdownIt-Anchor" href="#实现"></a> 实现</h1>
<h2 id="1-建库建表"><a class="markdownIt-Anchor" href="#1-建库建表"></a> 1、建库建表</h2>
<p>首先，我们在本地新建三个数据库名分别为<code>master</code>,<code>slave1</code>,<code>slave2</code>，我们的目前就是写入操作都是在<code>master</code>，查询是 <code>slave1,slave2</code><br>
因此我们在上一篇也就是<a href="https://www.jianshu.com/p/c44dc639cb93" target="_blank" rel="noopener">【SpringBoot2.0系列05】SpringBoot之整合Mybatis</a>基础上进行改动，<br>
我们在<code>master slave1 slave2</code>中都创建<code>user</code>表 其中初始化<code>salve1</code>库的<code>user</code>表数据为<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061637.jpg" alt=""><br>
<code>slave2</code>库的<code>user</code>表<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061626.jpg" alt=""><br>
具体的数据库脚本如下</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> master.user</span><br><span class="line">(</span><br><span class="line">	<span class="keyword">id</span> <span class="built_in">bigint</span> auto_increment <span class="keyword">comment</span> <span class="string">'主键'</span></span><br><span class="line">		primary <span class="keyword">key</span>,</span><br><span class="line">	age <span class="built_in">int</span> <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'年龄'</span>,</span><br><span class="line">	<span class="keyword">password</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'密码'</span>,</span><br><span class="line">	sex <span class="built_in">int</span> <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'性别'</span>,</span><br><span class="line">	username <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'用户名'</span></span><br><span class="line">)</span><br><span class="line"><span class="keyword">engine</span>=MyISAM <span class="keyword">collate</span>=utf8mb4_bin</span><br><span class="line">;</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> slave1.user</span><br><span class="line">(</span><br><span class="line">	<span class="keyword">id</span> <span class="built_in">bigint</span> auto_increment <span class="keyword">comment</span> <span class="string">'主键'</span></span><br><span class="line">		primary <span class="keyword">key</span>,</span><br><span class="line">	age <span class="built_in">int</span> <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'年龄'</span>,</span><br><span class="line">	<span class="keyword">password</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'密码'</span>,</span><br><span class="line">	sex <span class="built_in">int</span> <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'性别'</span>,</span><br><span class="line">	username <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'用户名'</span></span><br><span class="line">)</span><br><span class="line"><span class="keyword">engine</span>=MyISAM <span class="keyword">collate</span>=utf8mb4_bin</span><br><span class="line">;</span><br><span class="line"></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> slave1.user (<span class="keyword">id</span>, age, <span class="keyword">password</span>, sex, username) <span class="keyword">VALUES</span> (<span class="number">2</span>, <span class="number">22</span>, <span class="string">'admin'</span>, <span class="number">1</span>, <span class="string">'admin'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> slave2.user</span><br><span class="line">(</span><br><span class="line">	<span class="keyword">id</span> <span class="built_in">bigint</span> auto_increment <span class="keyword">comment</span> <span class="string">'主键'</span></span><br><span class="line">		primary <span class="keyword">key</span>,</span><br><span class="line">	age <span class="built_in">int</span> <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'年龄'</span>,</span><br><span class="line">	<span class="keyword">password</span> <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'密码'</span>,</span><br><span class="line">	sex <span class="built_in">int</span> <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'性别'</span>,</span><br><span class="line">	username <span class="built_in">varchar</span>(<span class="number">32</span>) <span class="literal">null</span> <span class="keyword">comment</span> <span class="string">'用户名'</span></span><br><span class="line">)</span><br><span class="line"><span class="keyword">engine</span>=MyISAM <span class="keyword">collate</span>=utf8mb4_bin</span><br><span class="line">;</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> slave2.user (<span class="keyword">id</span>, age, <span class="keyword">password</span>, sex, username) <span class="keyword">VALUES</span> (<span class="number">3</span>, <span class="number">19</span>, <span class="string">'uuu'</span>, <span class="number">2</span>, <span class="string">'user'</span>);</span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> slave2.user (<span class="keyword">id</span>, age, <span class="keyword">password</span>, sex, username) <span class="keyword">VALUES</span> (<span class="number">4</span>, <span class="number">18</span>, <span class="string">'bbbb'</span>, <span class="number">1</span>, <span class="string">'zzzz'</span>);</span><br></pre></td></tr></table></figure>
<h2 id="2-配置多数据源"><a class="markdownIt-Anchor" href="#2-配置多数据源"></a> 2、配置多数据源</h2>
<p>经过上面初始化 我们的<code>master.user</code>是一张空表，我们等下的插入与更新操作就在这上面，那么我们的查询操作就是在<code>slave1.user跟slave2.user</code>上面了。<br>
上面我们的数据库初始化工作完成了，接下来就是实现动态数据源的过程<br>
首先我们需要在我们的<code>application.yml</code>配置我们的三个数据源</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">server:</span></span><br><span class="line"><span class="attr">  port:</span> <span class="number">8989</span></span><br><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  datasource:</span></span><br><span class="line"><span class="attr">    master:</span></span><br><span class="line"><span class="attr">      password:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">      url:</span> <span class="attr">jdbc:mysql://127.0.0.1:3306/master?useUnicode=true&amp;characterEncoding=UTF-8</span></span><br><span class="line"><span class="attr">      driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">      username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">      type:</span> <span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">    cluster:</span></span><br><span class="line"><span class="attr">    - key:</span> <span class="string">slave1</span></span><br><span class="line"><span class="attr">      password:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">      url:</span> <span class="attr">jdbc:mysql://127.0.0.1:3306/slave1?useUnicode=true&amp;characterEncoding=UTF-8</span></span><br><span class="line"><span class="attr">      idle-timeout:</span> <span class="number">20000</span></span><br><span class="line"><span class="attr">      driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">      username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">      type:</span> <span class="string">com.zaxxer.hikari.HikariDataSource</span></span><br><span class="line"><span class="attr">    - key:</span> <span class="string">slave2</span></span><br><span class="line"><span class="attr">      password:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">      url:</span> <span class="attr">jdbc:mysql://127.0.0.1:3306/slave2?useUnicode=true&amp;characterEncoding=UTF-8</span></span><br><span class="line"><span class="attr">      driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">      username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">mybatis:</span></span><br><span class="line"><span class="attr">  mapper-locations:</span> <span class="attr">classpath:/mybatis/mapper/*.xml</span></span><br><span class="line"><span class="attr">  config-location:</span>  <span class="attr">classpath:/mybatis/config/mybatis-config.xml</span></span><br></pre></td></tr></table></figure>
<p>在上面我们配置了三个数据，其中第一个作为默认数据源也就是我们的<code>master</code>数据源。主要是写操作，那么读操作交给我们的<code>slave1跟slave2</code><br>
其中  master 数据源是一定要配置 作为我们的默认数据源，其次cluster集群中，其他的数据不配置也不会影响程序的运行（相当于单数据源），如果你想添加新的一个数据源 就在cluster下新增一个数据源即可，其中key为必须项，用于数据源的唯一标识，以及接下来切换数据源的标识。</p>
<h2 id="3-注册数据源"><a class="markdownIt-Anchor" href="#3-注册数据源"></a> 3、注册数据源</h2>
<p>在上面我们已经配置了三个数据源，但是这是我们自定义的配置，springboot是无法给我们自动配置，所以需要我们自己注册数据源.<br>
那么就要实现 <code>EnvironmentAware</code>用于读取上下文环境变量用于构建数据源，同时也需要实现 <code>ImportBeanDefinitionRegistrar</code>接口注册我们构建的数据源。<code>com.yukong.chapter5.register.DynamicDataSourceRegister</code>具体代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 动态数据源注册</span></span><br><span class="line"><span class="comment"> * 实现 ImportBeanDefinitionRegistrar 实现数据源注册</span></span><br><span class="line"><span class="comment"> * 实现 EnvironmentAware 用于读取application.yml配置</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicDataSourceRegister</span> <span class="keyword">implements</span> <span class="title">ImportBeanDefinitionRegistrar</span>, <span class="title">EnvironmentAware</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(DynamicDataSourceRegister.class);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 配置上下文（也可以理解为配置文件的获取工具）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Environment evn;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 别名</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> ConfigurationPropertyNameAliases aliases = <span class="keyword">new</span> ConfigurationPropertyNameAliases();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 由于部分数据源配置不同，所以在此处添加别名，避免切换数据源出现某些参数无法注入的情况</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        aliases.addAliases(<span class="string">"url"</span>, <span class="keyword">new</span> String[]&#123;<span class="string">"jdbc-url"</span>&#125;);</span><br><span class="line">        aliases.addAliases(<span class="string">"username"</span>, <span class="keyword">new</span> String[]&#123;<span class="string">"user"</span>&#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存储我们注册的数据源</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Map&lt;String, DataSource&gt; customDataSources = <span class="keyword">new</span> HashMap&lt;String, DataSource&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 参数绑定工具 springboot2.0新推出</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Binder binder;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * ImportBeanDefinitionRegistrar接口的实现方法，通过该方法可以按照自己的方式注册bean</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> annotationMetadata</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> beanDefinitionRegistry</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">registerBeanDefinitions</span><span class="params">(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 获取所有数据源配置</span></span><br><span class="line">        Map config, defauleDataSourceProperties;</span><br><span class="line">        defauleDataSourceProperties = binder.bind(<span class="string">"spring.datasource.master"</span>, Map.class).get();</span><br><span class="line">        <span class="comment">// 获取数据源类型</span></span><br><span class="line">        String typeStr = evn.getProperty(<span class="string">"spring.datasource.master.type"</span>);</span><br><span class="line">        <span class="comment">// 获取数据源类型</span></span><br><span class="line">        Class&lt;? extends DataSource&gt; clazz = getDataSourceType(typeStr);</span><br><span class="line">        <span class="comment">// 绑定默认数据源参数 也就是主数据源</span></span><br><span class="line">        DataSource consumerDatasource, defaultDatasource = bind(clazz, defauleDataSourceProperties);</span><br><span class="line">        DynamicDataSourceContextHolder.dataSourceIds.add(<span class="string">"master"</span>);</span><br><span class="line">        logger.info(<span class="string">"注册默认数据源成功"</span>);</span><br><span class="line">        <span class="comment">// 获取其他数据源配置</span></span><br><span class="line">        List&lt;Map&gt; configs = binder.bind(<span class="string">"spring.datasource.cluster"</span>, Bindable.listOf(Map.class)).get();</span><br><span class="line">        <span class="comment">// 遍历从数据源</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; configs.size(); i++) &#123;</span><br><span class="line">            config = configs.get(i);</span><br><span class="line">            clazz = getDataSourceType((String) config.get(<span class="string">"type"</span>));</span><br><span class="line">            defauleDataSourceProperties = config;</span><br><span class="line">            <span class="comment">// 绑定参数</span></span><br><span class="line">            consumerDatasource = bind(clazz, defauleDataSourceProperties);</span><br><span class="line">            <span class="comment">// 获取数据源的key，以便通过该key可以定位到数据源</span></span><br><span class="line">            String key = config.get(<span class="string">"key"</span>).toString();</span><br><span class="line">            customDataSources.put(key, consumerDatasource);</span><br><span class="line">            <span class="comment">// 数据源上下文，用于管理数据源与记录已经注册的数据源key</span></span><br><span class="line">            DynamicDataSourceContextHolder.dataSourceIds.add(key);</span><br><span class="line">            logger.info(<span class="string">"注册数据源&#123;&#125;成功"</span>, key);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// bean定义类</span></span><br><span class="line">        GenericBeanDefinition define = <span class="keyword">new</span> GenericBeanDefinition();</span><br><span class="line">        <span class="comment">// 设置bean的类型，此处DynamicRoutingDataSource是继承AbstractRoutingDataSource的实现类</span></span><br><span class="line">        define.setBeanClass(DynamicRoutingDataSource.class);</span><br><span class="line">        <span class="comment">// 需要注入的参数</span></span><br><span class="line">        MutablePropertyValues mpv = define.getPropertyValues();</span><br><span class="line">        <span class="comment">// 添加默认数据源，避免key不存在的情况没有数据源可用</span></span><br><span class="line">        mpv.add(<span class="string">"defaultTargetDataSource"</span>, defaultDatasource);</span><br><span class="line">        <span class="comment">// 添加其他数据源</span></span><br><span class="line">        mpv.add(<span class="string">"targetDataSources"</span>, customDataSources);</span><br><span class="line">        <span class="comment">// 将该bean注册为datasource，不使用springboot自动生成的datasource</span></span><br><span class="line">        beanDefinitionRegistry.registerBeanDefinition(<span class="string">"datasource"</span>, define);</span><br><span class="line">        logger.info(<span class="string">"注册数据源成功，一共注册&#123;&#125;个数据源"</span>, customDataSources.keySet().size() + <span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 通过字符串获取数据源class对象</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> typeStr</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Class&lt;? extends DataSource&gt; getDataSourceType(String typeStr) &#123;</span><br><span class="line">        Class&lt;? extends DataSource&gt; type;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (StringUtils.hasLength(typeStr)) &#123;</span><br><span class="line">                <span class="comment">// 字符串不为空则通过反射获取class对象</span></span><br><span class="line">                type = (Class&lt;? extends DataSource&gt;) Class.forName(typeStr);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// 默认为hikariCP数据源，与springboot默认数据源保持一致</span></span><br><span class="line">                type = HikariDataSource.class;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> type;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"can not resolve class with type: "</span> + typeStr); <span class="comment">//无法通过反射获取class对象的情况则抛出异常，该情况一般是写错了，所以此次抛出一个runtimeexception</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 绑定参数，以下三个方法都是参考DataSourceBuilder的bind方法实现的，目的是尽量保证我们自己添加的数据源构造过程与springboot保持一致</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> result</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> properties</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">bind</span><span class="params">(DataSource result, Map properties)</span> </span>&#123;</span><br><span class="line">        ConfigurationPropertySource source = <span class="keyword">new</span> MapConfigurationPropertySource(properties);</span><br><span class="line">        Binder binder = <span class="keyword">new</span> Binder(<span class="keyword">new</span> ConfigurationPropertySource[]&#123;source.withAliases(aliases)&#125;);</span><br><span class="line">        <span class="comment">// 将参数绑定到对象</span></span><br><span class="line">        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> &lt;T extends DataSource&gt; <span class="function">T <span class="title">bind</span><span class="params">(Class&lt;T&gt; clazz, Map properties)</span> </span>&#123;</span><br><span class="line">        ConfigurationPropertySource source = <span class="keyword">new</span> MapConfigurationPropertySource(properties);</span><br><span class="line">        Binder binder = <span class="keyword">new</span> Binder(<span class="keyword">new</span> ConfigurationPropertySource[]&#123;source.withAliases(aliases)&#125;);</span><br><span class="line">        <span class="comment">// 通过类型绑定参数并获得实例对象</span></span><br><span class="line">        <span class="keyword">return</span> binder.bind(ConfigurationPropertyName.EMPTY, Bindable.of(clazz)).get();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> clazz</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> sourcePath 参数路径，对应配置文件中的值，如: spring.datasource</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> &lt;T extends DataSource&gt; <span class="function">T <span class="title">bind</span><span class="params">(Class&lt;T&gt; clazz, String sourcePath)</span> </span>&#123;</span><br><span class="line">        Map properties = binder.bind(sourcePath, Map.class).get();</span><br><span class="line">        <span class="keyword">return</span> bind(clazz, properties);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * EnvironmentAware接口的实现方法，通过aware的方式注入，此处是environment对象</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> environment</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setEnvironment</span><span class="params">(Environment environment)</span> </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"开始注册数据源"</span>);</span><br><span class="line">        <span class="keyword">this</span>.evn = environment;</span><br><span class="line">        <span class="comment">// 绑定配置器</span></span><br><span class="line">        binder = Binder.get(evn);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码需要注意的是在<code>springboot2.x</code>系列中用于绑定的工具类如RelaxedPropertyResolver已经无法现在使用<code>Binder</code>代替。上面代码主要是读取application中数据源的配置，先读取<code>spring.datasource.maste</code>r构建默认数据源,然后在构建<code>cluster</code>中的数据源。<br>
在这里注册完数据源之后，我们需要通过@import注解把我们的数据源注册器导入到spring中 在启动类<code>Chapter5Application.java</code>加上如下注解<code>@Import(DynamicDataSourceRegister.class)</code>。<br>
其中我们用到了一个<code>DynamicDataSourceContextHolder</code> 中的静态变量来保存我们已经注册成功的数据源的<code>key</code>,至此我们的数据源注册就已经完成了。</p>
<h2 id="4-配置数据源上下文"><a class="markdownIt-Anchor" href="#4-配置数据源上下文"></a> 4、配置数据源上下文</h2>
<p>我们需要新建一个数据源上下文，用户记录当前线程使用的数据源的key是什么，以及记录所有注册成功的数据源的key的集合。对于线程级别的私有变量，我们首先<code>ThreadLocal</code>来实现。<br>
<code>com.yukong.chapter5.config.DynamicDataSourceContextHolder</code>代码取下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Auther</span>: yukong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2018/8/15 10:49</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: 数据源上下文</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicDataSourceContextHolder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Logger logger = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 存储已经注册的数据源的key</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> List&lt;String&gt; dataSourceIds = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 线程级别的私有变量</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> ThreadLocal&lt;String&gt; HOLDER = <span class="keyword">new</span> ThreadLocal&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">getDataSourceRouterKey</span> <span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> HOLDER.get();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">setDataSourceRouterKey</span> <span class="params">(String dataSourceRouterKey)</span> </span>&#123;</span><br><span class="line">        logger.info(<span class="string">"切换至&#123;&#125;数据源"</span>, dataSourceRouterKey);</span><br><span class="line">        HOLDER.set(dataSourceRouterKey);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 设置数据源之前一定要先移除</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">removeDataSourceRouterKey</span> <span class="params">()</span> </span>&#123;</span><br><span class="line">        HOLDER.remove();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 判断指定DataSrouce当前是否存在</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> dataSourceId</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">containsDataSource</span><span class="params">(String dataSourceId)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> dataSourceIds.contains(dataSourceId);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="5-动态数据源路由"><a class="markdownIt-Anchor" href="#5-动态数据源路由"></a> 5、动态数据源路由</h2>
<p>前面我们以及新建了数据源上下文，用于存储我们当前线程的数据源key那么怎么通知<code>spring</code>用key当前的数据源呢，查阅资料可知，<code>spring</code>提供一个接口，名为<code>AbstractRoutingDataSource</code>的抽象类，我们只需要重写<code>determineCurrentLookupKey</code>方法就可以，这个方法看名字就知道，就是返回当前线程的数据源的key，那我们只需要从我们刚刚的数据源上下文中取出我们的key即可，那么具体代码取下。<br>
<code>com.yukong.chapter5.config.DynamicRoutingDataSource</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Auther</span>: yukong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2018/8/15 10:47</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: 动态数据源路由配置</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicRoutingDataSource</span> <span class="keyword">extends</span> <span class="title">AbstractRoutingDataSource</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Logger logger = LoggerFactory.getLogger(DynamicRoutingDataSource.class);</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">determineCurrentLookupKey</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String dataSourceName = DynamicDataSourceContextHolder.getDataSourceRouterKey();</span><br><span class="line">        logger.info(<span class="string">"当前数据源是：&#123;&#125;"</span>, dataSourceName);</span><br><span class="line">        <span class="keyword">return</span> DynamicDataSourceContextHolder.getDataSourceRouterKey();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="6-通过aop注解实现动态数据源的切换"><a class="markdownIt-Anchor" href="#6-通过aop注解实现动态数据源的切换"></a> 6、通过aop+注解实现动态数据源的切换</h2>
<p>现在spring也已经知道通过key来取对应的数据源，我们现在只需要实现给对应的类或者方法设置他们的数据源的key，并且保存在数据源上下文中即可。这里我们采用注解来设置数据源，通过aop拦截并且保存到数据源上下中。<br>
我们新建一个标识数据源的注解<code>@DataSource</code>具体代码取下<br>
<code>com.yukong.chapter5.annotation.DataSource</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 切换数据注解 可以用于类或者方法级别 方法级别优先级 &gt; 类级别</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Target</span>(&#123;ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER&#125;)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Documented</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> DataSource &#123;</span><br><span class="line">    <span class="function">String <span class="title">value</span><span class="params">()</span> <span class="keyword">default</span> "master"</span>; <span class="comment">//该值即key值</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其中他的默认值是<code>master</code>,因为我们默认数据源的key也是<code>master</code>。也就是说如果你直接用注解，而不指定value的话，那么默认就使用master默认数据源。<br>
然后我们新建一个aop类来拦截。代码如下<br>
<code>com.yukong.chapter5.aop</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.yukong.chapter5.aop;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.yukong.chapter5.annotation.DataSource;</span><br><span class="line"><span class="keyword">import</span> com.yukong.chapter5.config.DynamicDataSourceContextHolder;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.JoinPoint;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.After;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.Aspect;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.Before;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.StringUtils;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicDataSourceAspect</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Before</span>(<span class="string">"@annotation(ds)"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">changeDataSource</span><span class="params">(JoinPoint point, DataSource ds)</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        String dsId = ds.value();</span><br><span class="line">        <span class="keyword">if</span> (DynamicDataSourceContextHolder.dataSourceIds.contains(dsId)) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Use DataSource :&#123;&#125; &gt;"</span>, dsId, point.getSignature());</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            logger.info(<span class="string">"数据源[&#123;&#125;]不存在，使用默认数据源 &gt;&#123;&#125;"</span>, dsId, point.getSignature());</span><br><span class="line">            DynamicDataSourceContextHolder.setDataSourceRouterKey(dsId);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@After</span>(<span class="string">"@annotation(ds)"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">restoreDataSource</span><span class="params">(JoinPoint point, DataSource ds)</span> </span>&#123;</span><br><span class="line">        logger.debug(<span class="string">"Revert DataSource : "</span> + ds.value() + <span class="string">" &gt; "</span> + point.getSignature());</span><br><span class="line">        DynamicDataSourceContextHolder.removeDataSourceRouterKey();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过aop拦截，获取注解上面的value的值key，然后取判断我们注册的keys集合中是否有这个key,如果没有，则使用默认数据源，如果有，则设置上下文中当前数据源的key为注解的value。<br>
7、测试<br>
最后我们在对应的方法上面加上注解来测试一下即可<br>
我们在UserMapper.java上面加上注解，并且进行测试。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Auther</span>: yukong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2018/8/13 19:47</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: UserMapper接口</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 新增用户</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@DataSource</span>  <span class="comment">//默认数据源</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">save</span><span class="params">(User user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新用户信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> user</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@DataSource</span>  <span class="comment">//默认数据源</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">update</span><span class="params">(User user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据id删除</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@DataSource</span>  <span class="comment">//默认数据源</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">deleteById</span><span class="params">(Long id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据id查询</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@DataSource</span>(<span class="string">"slave1"</span>)  <span class="comment">//slave1</span></span><br><span class="line">    <span class="function">User <span class="title">selectById</span><span class="params">(Long id)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 查询所有用户信息</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@DataSource</span>(<span class="string">"slave2"</span>)  <span class="comment">//slave2</span></span><br><span class="line">    <span class="function">List&lt;User&gt; <span class="title">selectAll</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码可以知道，我们的新增，修改，删除方法都是在默认数据master上，我们的id查询是在slave1，我们的查询所有在slave2，我们编写测试类来测试把。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Auther</span>: yukong</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span>: 2018/8/14 16:34</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>:</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="meta">@RunWith</span>(SpringJUnit4ClassRunner.class)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserMapperTest</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">save</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">new</span> User();</span><br><span class="line">        user.setUsername(<span class="string">"master"</span>);</span><br><span class="line">        user.setPassword(<span class="string">"master"</span>);</span><br><span class="line">        user.setSex(<span class="number">1</span>);</span><br><span class="line">        user.setAge(<span class="number">18</span>);</span><br><span class="line">        Assert.assertEquals(<span class="number">1</span>,userMapper.save(user));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = <span class="keyword">new</span> User();</span><br><span class="line">        user.setId(<span class="number">8L</span>);</span><br><span class="line">        user.setPassword(<span class="string">"newpassword"</span>);</span><br><span class="line">        <span class="comment">// 返回插入的记录数 ，期望是1条 如果实际不是一条则抛出异常</span></span><br><span class="line">        Assert.assertEquals(<span class="number">1</span>,userMapper.update(user));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">selectById</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        User user = userMapper.selectById(<span class="number">2L</span>);</span><br><span class="line">        System.out.println(<span class="string">"id:"</span> + user.getId());</span><br><span class="line">        System.out.println(<span class="string">"name:"</span> + user.getUsername());</span><br><span class="line">        System.out.println(<span class="string">"password:"</span> + user.getPassword());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteById</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Assert.assertEquals(<span class="number">1</span>,userMapper.deleteById(<span class="number">1L</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">selectAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;User&gt; users= userMapper.selectAll();</span><br><span class="line">        users.forEach(user -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">"id:"</span> + user.getId());</span><br><span class="line">            System.out.println(<span class="string">"name:"</span> + user.getUsername());</span><br><span class="line">            System.out.println(<span class="string">"password:"</span> + user.getPassword());</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>首先测试save方法，它将会把数据存到master库的user表，<br>
现在user表是空的，如图<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061705.jpg" alt=""><br>
运行save方法。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061715.jpg" alt=""></p>
<p>绿色，测试通过，并且日志提示数据源注册成功，一共三个。并且当前使用的master数据源，我们再去master数据库看看有没有数据。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061727.jpg" alt=""><br>
如上图，插入成功。<br>
新增方法测试完成了。我们在测试一下修改与删除。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061734.jpg" alt=""><br>
修改方法也测试通过，查看数据库。<img src="http://cdn.yukonga.cn/2019-05-07-061823.jpg" alt=""><br>
修改成功，删除方法我就不测试， 我们在测试测试，slave1跟slave2数据源的方法，<br>
首先测试<code>slave1</code>的主键查询方法，先看数据库 <code>slave1</code>有哪些数据。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061834.jpg" alt=""><br>
<code>slave1.user</code>就一条id为2 的数据并且id为2 的数据就slave1才有，我们测试一下能不能查到。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061845.jpg" alt=""><br>
运行通过，数据源为<code>slave1</code>并且数据也正确显示。<br>
最后我们来测试一下<code>slave2</code>的selectAll方法把，同样先看看<code>slave2.user</code>中有什么数据。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061853.jpg" alt=""><br>
从图中，得知<code>slave2.user</code>中有两条数据，id分别为3，4。接下来运行测试方法。<br>
结果如图。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-061902.jpg" alt=""><br>
日志提示数据源切换值<code>slave2</code>，并且id为3，4的数据也成功打印。<br>
那么至此我们的<strong>多数据源动态数据源</strong>就完成了。</p>
<p>主要的思路就是</p>
<ol>
<li>配置文件中配置多个数据源</li>
<li>启动类注册动态数据源</li>
<li>在需要的方法上使用注解指定数据源</li>
</ol>
<p>最后配套教程的代码全部在这里<br>
<a href="https://github.com/YuKongEr/SpringBoot-Study" target="_blank" rel="noopener">github https://github.com/YuKongEr/SpringBoot-Study</a>。麻烦点个star或者fork吧。</p>
<p>欢迎大家关注一下我的个人公众号。一起交流一起学习，有问必答。<br>
<img src="http://cdn.yukonga.cn/2019-05-07-055539.jpg" alt=""></p>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>喜欢就请博主喝个☕️吧</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="yukong 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="yukong 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yukong</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://www.yukonga.cn/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/" title="【SpringBoot2.0系列06】SpringBoot之多数据源动态切换数据源">http://www.yukonga.cn/2018/08/19/【SpringBoot2-0系列06】SpringBoot之多数据源动态切换数据源/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    
    

      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/SpringBoot/" rel="tag"><i class="fa fa-tag"></i> SpringBoot</a>
          
            <a href="/tags/DynamicDataSource/" rel="tag"><i class="fa fa-tag"></i> DynamicDataSource</a>
          
            <a href="/tags/DataSource/" rel="tag"><i class="fa fa-tag"></i> DataSource</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/18/【SpringBoot2-0系列05】SpringBoot之整合Mybatis/" rel="next" title="【SpringBoot2.0系列05】SpringBoot之整合Mybatis">
                <i class="fa fa-chevron-left"></i> 【SpringBoot2.0系列05】SpringBoot之整合Mybatis
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/20/【SpringBoot2-0系列07】SpringBoot之redis使用（Lettuce版本）/" rel="prev" title="【SpringBoot2.0系列07】SpringBoot之redis使用（Lettuce版本）">
                【SpringBoot2.0系列07】SpringBoot之redis使用（Lettuce版本） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="yukong">
            
              <p class="site-author-name" itemprop="name">yukong</p>
              <div class="site-description motion-element" itemprop="description">你若对得起时间，时间便对得起你</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/YuKongEr" title="GitHub &rarr; https://github.com/YuKongEr" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:yukongcode@gmail.com" title="E-Mail &rarr; mailto:yukongcode@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.jianshu.com/u/bc2e35b66293" title="简书 &rarr; https://www.jianshu.com/u/bc2e35b66293" rel="noopener" target="_blank"><i class="fa fa-fw fa-skype"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/xp541130126" title="csdn &rarr; https://blog.csdn.net/xp541130126" rel="noopener" target="_blank"><i class="fa fa-fw fa-vk"></i>csdn</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#实现"><span class="nav-number">1.</span> <span class="nav-text"> 实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-建库建表"><span class="nav-number">1.1.</span> <span class="nav-text"> 1、建库建表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-配置多数据源"><span class="nav-number">1.2.</span> <span class="nav-text"> 2、配置多数据源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-注册数据源"><span class="nav-number">1.3.</span> <span class="nav-text"> 3、注册数据源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-配置数据源上下文"><span class="nav-number">1.4.</span> <span class="nav-text"> 4、配置数据源上下文</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-动态数据源路由"><span class="nav-number">1.5.</span> <span class="nav-text"> 5、动态数据源路由</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-通过aop注解实现动态数据源的切换"><span class="nav-number">1.6.</span> <span class="nav-text"> 6、通过aop+注解实现动态数据源的切换</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yukong</span>

  

  
</div>
<div class="BbeiAn-info">
浙ICP备 -
<a target="_blank" href="http://www.miitbeian.gov.cn">19015067号</a>

</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
      您是访问本站的第&nbsp
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      &nbsp 位朋友
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
      本站总共访问&nbsp
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
    appKey: 'n3ohmj1CGAM1GUfp6SqF4LXh',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
                'X-LC-Key': 'n3ohmj1CGAM1GUfp6SqF4LXh',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
